package com.b2;

import com.alibaba.fastjson.JSONObject;
import com.b2.exception.BaseException;
import com.b2.pojo.dto.PushDTO;
import com.b2.pojo.dto.TemplateData;
import com.b2.properties.WeChatProperties;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@SpringBootTest
public class PushBizService {

    private OkHttpClient okHttpClient = new OkHttpClient();

    public static final String WX_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type={grant_type}&appid={appid}&secret={secret}";

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 发送方法
     * @param pushDTO 所需数据
     * @return responseEntity
     */
    @SneakyThrows
    public ResponseEntity<String> pushOneUser(PushDTO pushDTO) {
        final String SEND_INFO_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";

        RestTemplate restTemplate = new RestTemplate();
        String appId = "wx574727e2c7a549a2";
        String appSecret = "80eee7ed484618939795bfbd8059c92a";
        // 获取accessTokenJson
        String accessTokenJson = getAccessTokenJSON(appId, appSecret);
        // 获取accessToken
        JSONObject jsonObject = JSONObject.parseObject(accessTokenJson);
        String accessToken = jsonObject.getString("access_token");
        // 获取过期时间
        Long expiresTime = jsonObject.getLong("expires_in");
        System.out.println(accessToken);
        String url = SEND_INFO_URL + accessToken;

        return restTemplate.postForEntity(url, pushDTO, String.class);
    }


    /**
     * 测试方法
     */
    @Test
    public void test(){
        String openid = "oIzyv4t__XTeHhUJku3E_OPI3f1A";
        String templateId ="Zp8PQMRWZMtbMFjisrCUMnws-d926OkneRZrtKXEhS0";
        //拼接推送的模版
        PushDTO pushDTO = new PushDTO();
        //用户的openId
        pushDTO.setTouser(openid);
        pushDTO.setTemplate_id(templateId);
        Map<String, TemplateData> data = new HashMap<>();
        data.put("thing4", new TemplateData("新婴儿奶瓶"));
        data.put("thing5", new TemplateData("11231323"));
        data.put("thing6", new TemplateData("0.01"));
        data.put("time7", new TemplateData("2023-02-16"));
        pushDTO.setData(data);
        System.out.println("发送的模板" + data);
        Date date = new Date();
        PushBizService pushBizService = new PushBizService();
        ResponseEntity<String> stringResponseEntity = pushBizService.pushOneUser(pushDTO);
        System.out.println(stringResponseEntity);
    }


    /**
     * 查微信AcessToken,返回JSON值
     *
     * @param appId
     * @param appSecret
     * @return
     * @throws Exception
     */
    private String getAccessTokenJSON(String appId, String appSecret) throws Exception {
        String json = okHttpClient.newCall(
                new Request.Builder().url("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                        + appId + "&secret=" + appSecret).build())
                .execute().body().string();
        JSONObject jsonObject = JSONObject.parseObject(json);
        Integer errcode = jsonObject.getInteger("errcode");
        if (errcode == null || errcode == 0) {
            return json;
        } else {
            log.info("[微信 getAccessToken] 回复失败 回复报文：" + json);
            throw new BaseException("微信获取access_token失败");
        }
    }

}
